package org.yelongframework.model.support.mybatis.sql.fragment.condition;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.ibatis.annotations.Param;
import org.yelongframework.model.support.mybatis.interceptor.MybatisPlaceholderMapInterceptor;
import org.yelongframework.model.support.mybatis.sql.fragment.MybatisSqlFragment;
import org.yelongframework.model.support.mybatis.sql.fragment.MybatisSqlPlaceholderable;
import org.yelongframework.sql.fragment.condition.combination.CombinationConditionSqlFragment;

/**
 * mybatis组合条件SQL片段
 * <p>
 * 该对象作为mapper的参数。可以在mapper.xml中使用${condition}获取其条件片段
 * 和${isCondition}来判断是否存在条件片段<br/>
 * 如果需要使用{@link Param} 应该加入{@link MybatisPlaceholderMapInterceptor}
 * 拦截器，否则会出现无法获取参数问题
 * </p>
 * 
 * @since 1.0.0
 */
public interface MybatisCombinationConditionSqlFragment
		extends CombinationConditionSqlFragment, MybatisSqlFragment, MybatisSqlPlaceholderable {

	/**
	 * mybatis映射文件中取条件的占位符 。${condition}
	 */
	public static final String CONDITION_FLAG = "condition";

	/**
	 * mybatis映射文件中判断是否存在条件。。&lt;if&gt; test = " isCondition
	 * ">${condition}&lt;/if&gt;
	 */
	public static final String IS_CONDITION_FLAG = "isCondition";

	/**
	 * @return 条件
	 */
	default String getCondition() {
		return getMybatisBoundSql().getMybatisSql();
	}

	/**
	 * @return 是否存在条件
	 */
	default boolean isIsCodition() {
		return isEmpty();
	}

	@Override
	default String[] getMyBatisPlaceholderAll() {
		return ArrayUtils.toArray(CONDITION_FLAG, IS_CONDITION_FLAG);
	}

	@Override
	default Object getMyBatisPlaceholderValue(String placeholder) {
		if (placeholder.equalsIgnoreCase(CONDITION_FLAG)) {
			return getCondition();
		} else if (placeholder.equalsIgnoreCase(IS_CONDITION_FLAG)) {
			return !isIsCodition();
		} else {
			return null;
		}
	}

}
